/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.context.core;

import io.iec.edp.caf.core.context.BizContext;
import io.iec.edp.caf.core.context.BizContextManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 请求结束时，检测业务上下文变更并更新
 * @author wangyandong
 * @date 2020/1/11 19:40
 *
 */
public class BizContextUpdateService implements InitializingBean, DisposableBean {
    private ThreadPoolTaskExecutor executor;
    private BizContextManager manager;

    public BizContextUpdateService(BizContextManager manager) {
        this.manager = manager;
    }

    public void update(BizContext context){
        if(context!=null && context.getItemsChanged()){
            executor.execute(() -> {
                manager.update(context);
            });
        }
    }

    @Override
    public void afterPropertiesSet() {
        if (this.executor == null) {
            this.executor = this.createDefaultTaskExecutor();
        }
    }

    protected ThreadPoolTaskExecutor createDefaultTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.initialize();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(8);
        executor.setKeepAliveSeconds(10);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("BizContext executor thread: ");
        return executor;
    }

    @Override
    public void destroy() throws Exception {
        if (this.executor instanceof DisposableBean) {
            ((DisposableBean)this.executor).destroy();
        }
    }
}
